package com.alinesno.cloud.common.web.base.advice;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.common.core.context.ApplicationContextProvider;
import com.alinesno.cloud.common.facade.pageable.DatatablesPageBean;
import com.alinesno.cloud.common.web.base.advice.plugins.PluginRegistry;

/**
 * 数据切面
 * @author WeiXiaoJin
 * @since 2018年9月23日 下午6:28:15
 */
@Order(1)
@ControllerAdvice
public class DatagridResponseBodyAdvice implements ResponseBodyAdvice<DatatablesPageBean> {

	// 日志记录
	private final static Logger log = LoggerFactory.getLogger(DatagridResponseBodyAdvice.class);
	
	/**
	 * 拦截数据
	 */
	@Override
	public DatatablesPageBean beforeBodyWrite(DatatablesPageBean baseGridData, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> classes, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
		
		// 兼容bootstrap_table
		Object dataObject = baseGridData.isBootstrapTable()?baseGridData.getRows():baseGridData.getData(); 
		log.trace("is bootstrap table:{}" , baseGridData.isBootstrapTable());
		
		if(dataObject == null) {
			return baseGridData ; 
		}
		
		try {
			TranslateCode convertCode = methodParameter.getMethod().getAnnotation(TranslateCode.class);
			String pluginName = convertCode.plugin() ; 
			
			if(dataObject instanceof List) {
			
				List<JSONObject> array = JSON.parseArray(JSONObject.toJSONString(dataObject) , JSONObject.class) ; 
				for(JSONObject node : array) {
					// log.debug("node:{}" , node.toString());
					for(Class<?> c : PluginRegistry.query()) {
						
						TranslatePlugin plugin = (TranslatePlugin) ApplicationContextProvider.getBean(c) ; 
						
						try {
							plugin.translate(node, convertCode); 
						}catch(Exception e) {
							log.error("代码{} , 代码转换异常:{}" , pluginName , e);
						}
						
						if(StringUtils.isNotBlank(pluginName)) {
							TranslatePlugin selfP = (TranslatePlugin) ApplicationContextProvider.getBean(pluginName) ; 
							try {
								selfP.translate(node, convertCode);
							}catch(Exception e) {
								log.error("插件{} , 代码转换异常:{}" , pluginName , node);
							}
						}
					}
				}
				
				// 兼容bootstrap_table 
				if(baseGridData.isBootstrapTable()) {
					baseGridData.setRows(array);	
				} else {
					baseGridData.setData(array);	
				}
				
			}
		} catch (Exception e) {
			log.error("代码转换异常:{}" , e);
		}
		
		return baseGridData;
	}

	@Override
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> classes) {
		TranslateCode convertCode = methodParameter.getMethod().getAnnotation(TranslateCode.class);
		return convertCode == null ? false : true;
	}

}